<?php

namespace App\Api\V1\Controllers;

use App\Models\Points;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthorizationController extends Controller
{
    protected $guard = 'api';

    /**
     * 发送验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCode(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
        ]);

        $mobile = $request->mobile;

        if (!is_mobile($mobile))
            return response()->json([
                'status_code' => 0,
                'message'     => '手机号格式不正确'
            ]);

        $user = User::where('mobile', $mobile)->rightJoin('love_department_users as b', 'b.user_id', 'love_users.id')->count();

        if (!$user)
            return response()->json([
                'status_code' => 0,
                'message'     => '用户不存在'
            ]);

        $code = mt_rand(100000,999999);

        $content = "您的验证码是：{$code}，如非本人操作请忽视。";

        $result = sms($mobile, $content);
        if ($result) {
            $redis_key = 'user:login:' . $mobile;
            $flag      = Redis::SET($redis_key, $code);

            if ($flag) {
                Redis::EXPIRE($redis_key, 300);
                $status_code = 1;
                $message     = '发送成功';
            } else {
                $status_code = 0;
                $message     = '发送失败';
            }
        } else {
            $status_code = 0;
            $message     = '发送失败';
        }

        return response()->json([
            'status_code' => $status_code,
            'message'     => $message,
            'code'        => $code
        ]);
    }

    /*
     * 登录
     *
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'code'   => 'required'
        ]);

        $mobile = $request->mobile;
        $code   = $request->code;

        if (!is_mobile($mobile))
            return response()->json([
                'status_code' => 0,
                'message'     => '手机号格式不正确',
            ]);

        $redis_key = 'user:login:' . $mobile;

        if ($code != Redis::GET($redis_key))
            return response()->json([
                'status_code' => 0,
                'message'     => '验证码不正确',
            ]);


        $user = User::where('mobile', $mobile)->first();


        if (!$user) {

            //throw new BadRequestHttpException('用户不存在', null, 1001);

            return response()->json([
                'status_code' => 1001,
                'message'     => '用户不存在',
            ]);

        }

        try {
            if (!$token = Auth::guard($this->guard)->login($user)) {
                return response()->json([
                    'status_code' => 1002,
                    'message'     => '登录失败',
                ]);
            }

            Redis::DEL($redis_key);

            $ttl = Auth::guard($this->guard)->factory()->getTTL() * 60;
            $time = time();

            $expires_in = $ttl + $time;
            $refresh_expires_in = 2 * $ttl + $time;

            return response()->json([
                'status_code' => 1,
                'message'     => '登录成功',
                'data'        => compact('token', 'expires_in', 'refresh_expires_in')
            ]);

        } catch (JWTException $e) {
            return response()->json([
                'status_code' => 1002,
                'message'     => '登录失败',
            ]);
        }

    }

    /**
     * 刷新token
     *
     * @return mixed
     */
    public function refreshToken()
    {

        try {
            if (!$token = Auth::guard($this->guard)->refresh()) {
                return response()->json([
                    'status_code' => 1003,
                    'message'     => '失败',
                ]);
            }

            $ttl = Auth::guard($this->guard)->factory()->getTTL() * 60;
            $time = time();

            $expires_in = $ttl + $time;
            $refresh_expires_in = 2 * $ttl + $time;

            return response()->json([
                'status_code' => 1,
                'message'     => '成功',
                'data'        => compact('token', 'expires_in', 'refresh_expires_in')
            ]);

        } catch (JWTException $e) {
            return response()->json([
                'status_code' => 1003,
                'message'     => '失败',
            ]);
        }
    }

    /**
     * 个人信息
     *
     * @return User|null
     */
    public function user()
    {

        try {
            if (!$user = Auth::guard($this->guard)->user()) {
                return response()->json([
                    'status_code' => 1004,
                    'message'     => '失败',
                ]);
            }

            $points = Points::where('user_id', $user['id'])->first();

            $user['points'] = $points ? $points->points : 0;
            $user['avatar'] = url("uploads/".$user['avatar']);
            $user['birthday'] = date('Y-m-d', strtotime($user['birthday']));

            if ($user['mobile'])
                $user['mobile'] = substr_replace($user['mobile'], '****', 3, 4);

            return response()->json([
                'status_code' => 1,
                'message'     => '成功',
                'data'        => $user,
            ]);

        } catch (JWTException $e) {
            return response()->json([
                'status_code' => 1004,
                'message'     => '失败',
            ]);
        }

    }

    /**
     * 退出
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        Auth::guard($this->guard)->logout();
        return response()->json([
            'status_code' => 1,
            'message'     => '退出成功',
        ]);
    }





}
